package com.example.demo.exception;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.bean.Result;
import com.google.common.base.Objects;

/**
 * controller 增强器
 *
 * @author sam
 * @since 2017/7/17
 */
@ControllerAdvice
public class MyControllerAdvice {
	private static final Logger LOGGER = LoggerFactory.getLogger(MyControllerAdvice.class);
	/**
	 * 全局异常捕捉处理
	 * 
	 * @param ex
	 * @return
	 */
	@ResponseBody
	@ExceptionHandler(value = Exception.class)
	public Result errorHandler(Exception ex) {
		Result result = new Result();
		result.setCode("500");
		result.setMsg(ex.getMessage());
		LOGGER.error("全局异常捕捉:", ex);
		return result;
	}

	/**
	 * 拦截捕捉自定义异常 MyException.class
	 * 
	 * @param ex
	 * @return
	 */
	@ResponseBody
	@ExceptionHandler(value = SPIPException.class)
	public Result myErrorHandler(SPIPException ex) {
		Result result = new Result();
		if (StringUtils.isNotBlank(ex.getMessageCode())) {
			result.setCode(ex.getMessageCode());
		} else {
			result.setCode("500");
		}
		result.setMsg(ex.getMessage());
		if (Objects.equal(result.getCode(), "500"))
			LOGGER.error("捕捉自定义异常:", ex);
		return result;
	}

}
